﻿#region 文件信息

/*----------------------------------------------------------------
//
// 文件名称：
// 文件功能描述：
// 设计要求：
//
// 文 件 名：    LoginViewModel
// 创建者：      杨程
// 创建日期：	    2022/12/20 21:18:36

//----------------------------------------------------------------*/

#endregion

using Vampirewal.Admin.Client.ViewModels.Services;

namespace Vampirewal.Admin.Client.ViewModels.ViewModel;

/// <summary>
/// 登陆VM
/// </summary>
[VampirewalIoCRegister(ClientViewModelKeys.LoginViewModel)]
public partial class LoginViewModel : BillVM<Sys_UserVO>
{
    private IRpcService RpcService { get; set; }

    private IVampirewalCoreDialogMessage Dialog { get; set; }

    private IApplicationService ApplicationService { get; set; }    

    /// <summary>
    ///
    /// </summary>
    public LoginViewModel(IRpcService rpcService, IVampirewalCoreDialogMessage dialog, IUpgradeService upgradeService, IApplicationService application) : base()
    {
        //upgradeService.Update();
        RpcService = rpcService;
        Dialog = dialog;
        ApplicationService=application;
        //构造函数
        Title = "登陆";
        //BuildImage();

        BackgroundImageSource = "pack://application:,,,/Vampirewal.Admin.Client;component/Logo.png";

        UserOption = VampirewalCoreContext.GetInstance().GetOptions<UserOptions>();

        if (UserOption.IsRemeber)
        {
            Entity.UserId = UserOption.LoginName;
            Entity.Password = UserOption.Password;

            if (UserOption.IsAutoLogin)
            {
                Login();
            }
        }

        RemeberActionsCommand = new IVampirewalCoreEventCommand[]
        {
            //new EventAction<object, RoutedEventArgs>("Checked", (sender, e) =>
            //{
            //    if((sender as CheckBox).IsChecked==true)
            //    {
            //    }
            //})

            new VampirewalCoreEventCommand("Checked","",new RelayCommand<object>((sender) =>
            {

            }))
        };

        AutoLoginActionsCommand = new IVampirewalCoreEventCommand[]
        {
            //new EventAction<object, RoutedEventArgs>("Checked", (sender, e) =>
            //{
            //})

            new VampirewalCoreEventCommand("Checked","",new RelayCommand<object>((sender) =>
            {

            }))
        };
    }

    #region [     属性     ]

    private bool _IsLoading = false;

    /// <summary>
    ///
    /// </summary>
    public bool IsLoading
    {
        get
        {
            return _IsLoading;
        }
        set
        {
            _IsLoading = value;
            OnPropertyChanged();
        }
    }

    //private BitmapImage _BackgroundImage;

    //public BitmapImage BackgroundImage
    //{
    //    get { return _BackgroundImage; }
    //    set { _BackgroundImage = value; OnPropertyChanged(); }
    //}

    public IVampirewalCoreEventCommand[] RemeberActionsCommand { get; set; }
    public IVampirewalCoreEventCommand[] AutoLoginActionsCommand { get; set; }

    private UserOptions _UserOption;

    /// <summary>
    ///
    /// </summary>
    public UserOptions UserOption
    {
        get
        {
            return _UserOption;
        }
        set
        {
            _UserOption = value;
            OnPropertyChanged();
        }
    }

    #endregion

    #region [     私有方法     ]

    private string _BackgroundImageSource;

    public string BackgroundImageSource
    {
        get { return _BackgroundImageSource; }
        set { _BackgroundImageSource = value; OnPropertyChanged(); }
    }



    //private void BuildImage()
    //{
    //    BackgroundImage = new BitmapImage();

    //    BackgroundImage.BeginInit();

    //    BackgroundImage.UriSource = new Uri("pack://application:,,,/Vampirewal.Admin.Client;component/Logo.png");

    //    BackgroundImage.DecodePixelWidth = 800;

    //    BackgroundImage.EndInit();

    //    BackgroundImage.Freeze();
    //}

    private void SetGlobalToken(object obj)
    {
        var type = obj.GetType();

        var Props = type.GetProperties();

        foreach (var item in Props)
        {
            var value = item.GetValue(obj);
            string name = item.Name;

            VampirewalCoreContext.GetInstance().AddContext(name, value);
        }
    }

    #endregion

    #region [     Command命令     ]

    /// <summary>
    /// 登陆命令
    /// </summary>
    [RelayCommand]
    public async void Login()
    {
        if (string.IsNullOrEmpty(Entity.UserId) || string.IsNullOrEmpty(Entity.Password))
        {
            return;
        }

        IsLoading = true;

        bool result = await Task<bool>.Run(() =>
        {
            bool IsOk = false;

            RpcService.CallApi<Sys_UserDTO>(RpcMethod.Login, InvokeOptionUtil.Fast_WaitInvoke_10s, (response) =>
            {
                VampirewalCoreContext.GetInstance().AddContext("CurLoginUser", response);

                SetGlobalToken(response);

                #region 根据当前登陆用户的权限获取菜单

                RpcService.CallApi<List<Sys_MenuDTO>>(RpcMethod.GetLoginUserMenus, InvokeOptionUtil.Fast_WaitInvoke_10s, (response) =>
                {
                    List<Sys_MenuVO> currentMenu = new List<Sys_MenuVO>();

                    foreach (var item in response)
                    {
                        var vo = item.SimpleMap<Sys_MenuVO>();

                        currentMenu.Add(vo);
                    }

                    VampirewalCoreContext.GetInstance().AddContext("ClientMenu", currentMenu);

                    #region 获取字典类型

                    RpcService.CallApi<List<Sys_DicCategoryDTO>>(RpcMethod.GetAllDicCategory, InvokeOptionUtil.Fast_WaitInvoke_10s, (response) =>
                    {
                        List<Sys_DicCategoryVO> CurDicCategory = new List<Sys_DicCategoryVO>();
                        foreach (var item in response)
                        {
                            var vo = item.SimpleMap<Sys_DicCategoryVO>();
                            CurDicCategory.Add(vo);
                        }

                        VampirewalCoreContext.GetInstance().AddContext("DicCategory", CurDicCategory);
                    }, (ex) =>
                    {
                    });

                    #endregion

                    IsOk = true;
                }, (ex) =>
                {
                });

                #endregion
            }, (ex) =>
            {
                ApplicationService.BeginInvoke(() =>
                {
                    Dialog.ShowPopupWindow(new Core.WindoSetting.PopupWindowSetting()
                    {
                        Message=ex.Message,
                        OwnerWindow=WindowsManager.GetInstance().GetWindow(ViewId),
                        Type = Core.WindoSetting.MessageType.Error
                    });
                });
            }, Entity.UserId, Entity.Password);

            IsLoading = false;

            return IsOk;
        });

        #region [     跳转MainView     ]

        if (result)
        {
            if (UserOption.IsRemeber)
            {
                UserOption.LoginName = Entity.UserId;
                UserOption.Password = Entity.Password;
            }
            else
            {
                UserOption.LoginName = "";
                UserOption.Password = "";
                UserOption.IsAutoLogin = false;
            }
            VampirewalCoreContext.GetInstance().SetOptions(UserOption);

            var loginview = WindowsManager.GetInstance().Windows["LoginWindow"];
            //loginview.Visibility = Visibility.Collapsed;
            loginview.ShowInTaskbar = false;

            var WinResult = (bool?)WindowsManager.GetInstance().OpenDialogWindow(ClientViewKeys.MainView);

            if (WinResult == null)
            {
                //loginview.Visibility = Visibility.Visible;
                loginview.ShowInTaskbar = true;
            }
            else if (WinResult == false)
            {
                ApplicationService.Shutdown();
            }
        }

        #endregion
    }

    
    #endregion
}